package com.zmn.oms.common.utils;

import java.util.Optional;

/**
 * 类描述：获取异常堆栈信息
 *
 * @author lhl
 * @date 2020/06/09 14:30
 */
public final class ExceptionUtil {

    /**
     * 获取异常堆栈
     * @param e
     * @return
     */
    public static String getStackTrace(Throwable e) {
        return getStackTrace(e, null);
    }

    /**
     * 获取异常堆栈
     * @param e
     * @return
     */
    public static String getStackTrace(Throwable e, String msg) {
        StringBuilder traceBuilder = new StringBuilder();

        if (msg != null) {
            traceBuilder.append(msg).append("\n");
        }

        // 异常基本信息
        traceBuilder.append(e.getClass().getName())
                .append(": ")
                .append(Optional.ofNullable(e.getMessage()).orElse("null"))
                .append("\n");


        StackTraceElement[] traceElements = e.getStackTrace();
        if (traceElements != null && traceElements.length > 0) {
            for (StackTraceElement traceElement : traceElements) {
                traceBuilder.append("\tat ")
                        .append(traceElement.toString())
                        .append("\n");
            }
        }

        return traceBuilder.toString();
    }


    /**
     * 私有构造器，防止外部实例化
     */
    private ExceptionUtil() {}
}
